﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Ttifa.Entity;
using Ttifa.Infrastructure;
using Ttifa.Service;
using Ttifa.WebApiBase;
using Ttifa.WebApiBase.Filters;

namespace Ttifa.WebApi.Controllers
{
    [Login]
    public class TaskController : ApiController
    {
        public ApiResult Put(CronTask model)
        {
            var service = Ninject.GetService<ICronTaskService>();
            model.CreatedTime = DateTime.Now;
            model.Status = TaskState.STOP;
            service.Create(model);
            return new ApiResult();
        }

        public ApiResult Post(CronTask model)
        {
            var service = Ninject.GetService<ICronTaskService>();
            var theTask = service.Get(model.Id);
            if (theTask == null)
                return new ApiResult(ApiStatus.Fail, "任务不存在");

            theTask.ModifyTime = DateTime.Now;
            theTask.TaskName = model.TaskName;
            theTask.TaskParam = model.TaskParam;
            theTask.CronExpressionString = model.CronExpressionString;
            theTask.ApiUri = model.ApiUri;
            theTask.Remark = model.Remark;
            service.Update(theTask);
            return new ApiResult();
        }

        public ApiResult SetStatus(int id, TaskState state)
        {
            var service = Ninject.GetService<ICronTaskService>();
            var theTask = service.Get(id);
            if (theTask == null)
                return new ApiResult(ApiStatus.Fail, "任务不存在");

            theTask.Status = state;
            service.Update(theTask);
            return new ApiResult();
        }

        [ApiLog]
        public ApiResult Get(int pagesize, int pageindex)
        {
            var service = Ninject.GetService<ICronTaskService>();
            var result = new ApiResult(ApiStatus.OK, "success");
            result.Page = new ApiResultPage();
            var list = service.Page(t => t.Status != TaskState.DELETE, pagesize, pageindex, out result.Page.PageCount, out result.Page.Total);
            result.Data = list;

            return result;
        }
    }
}
